﻿using System.Net.Http.Headers;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace Niaofei.Redis
{
    internal class RedisJsonSerializer
    {
        private readonly JsonSerializerOptions _option;

        public RedisJsonSerializer()
        {
            _option = new JsonSerializerOptions()
            {
                WriteIndented = true,
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            };
        }

        public byte[] Serialize<TValue>(TValue value)
        {
            var text = JsonSerializer.Serialize(value, _option);

            var result = Encoding.UTF8.GetBytes(text);

            return result;
        }

        public TValue Deserialize<TValue>(string value)
        {
            var result = JsonSerializer.Deserialize<TValue>(value, _option);

            if (result != null)
            {
                return result;
            }

            throw new InvalidOperationException($"{nameof(RedisJsonSerializer)}:Json序列化失败");
        }

        public TValue Deserialize<TValue>(byte[] bytes)
        {
            var text = Encoding.UTF8.GetString(bytes);

            var result = JsonSerializer.Deserialize<TValue>(text, _option);

            if (result != null)
            {
                return result;
            }

            throw new InvalidOperationException($"{nameof(RedisJsonSerializer)}:Json序列化失败");
        }
    }
}
